package ar.com.lemil.bb.http;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Hashtable;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

import ar.com.lemil.bb.http.vo.HttpRequest;
import ar.com.lemil.bb.utils.log.ILogger;

public class HttpMultipartRequestUtils {
	static final String BOUNDARY = "----WebKitFormBoundaryxEXS5qFmQFdB7IhQ";

	ILogger logger;

	public void setLogger(ILogger screen) {
		this.logger = screen;
	}

	public byte[] getPostBytes() {
		return postBytes;
	}

	byte[] postBytes = null;
	String url = null;

	public HttpMultipartRequestUtils(String url, Hashtable params, String fileField,
			String fileName, String fileType, byte[] fileBytes)
			throws Exception {
		this.url = url;
		this.postBytes = buildPost(params, fileField, fileName, fileType,
				fileBytes);
	}
	
	public HttpMultipartRequestUtils(String url, Hashtable params, HttpRequest[] attachments)
			throws Exception {
		this.url = url;
		this.postBytes = buildPost(params, attachments);
	}
	
	private byte[] buildPost(Hashtable params, String field, String name,
			String mimeType, byte[] data) {

		HttpRequest[] attachments = new HttpRequest[1];
		HttpRequest ra = new HttpRequest(name, mimeType, field,
				data);
		attachments[0] = ra;
		return buildPost(params, attachments);

	}

	private byte[] buildPost(Hashtable params, HttpRequest[] attachments) {

		StringBuffer res = new StringBuffer();

		if (params != null) {
			Enumeration keys = params.keys();
			while (keys.hasMoreElements()) {
				String key = (String) keys.nextElement();
				String value = (String) params.get(key);

				res.append("--").append(BOUNDARY).append("\r\n");
				res.append("Content-Disposition: form-data; name=\"").append(
						key).append("\"\r\n").append("\r\n");
				res.append(value).append("\r\n");
			}
		}

		for (int i = 0; i < attachments.length; i++) {

			HttpRequest ra = attachments[i];

			String fileField = ra.getField();
			String fileName = ra.getName();
			String fileType = ra.getMimeType();
			byte[] fileBytes = ra.getData();

			if (fileBytes != null) {
				res.append("--").append(BOUNDARY).append("\r\n");
				res.append("Content-Disposition: form-data; name=\"").append(
						fileField).append("\"; filename=\"").append(fileName)
						.append("\"\r\n").append("Content-Type: ").append(
								fileType).append("\r\n\r\n");
				String sfile = new String(fileBytes);
				res.append(sfile).append("\r\n");
			}

		}
		//
		res.append("--").append(BOUNDARY).append("--").append("\r\n");

		return res.toString().getBytes();
	}

	public String sendMultipart() throws Exception {
		HttpConnection hc = null;
		InputStream is = null;
		String res = null;
		OutputStream dout = null;
		InputStreamReader isr = null;
		try {

			//logger.log("url:" + url);

			hc = (HttpConnection) Connector.open(url);
			hc.setRequestMethod(HttpConnection.POST);

			// screen.log("method post");

			hc
					.setRequestProperty("User-Agent",
							"Profile/MIDP-2.0 Configuration/CLDC-1.0 ReclamosMobiles/1.0");
			// screen.log("method 1");
			hc.setRequestProperty("Content-Language", "en-US");
			// screen.log("method 2");
			hc.setRequestProperty("Content-Type",
					"multipart/form-data; boundary=" + BOUNDARY);
			// screen.log("method 3");
			hc.setRequestProperty("Content-Lenght", "" + postBytes.length);
			// screen.log("method 4");
			hc
					.setRequestProperty(
							"Accept",
							"application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
			// hc.setRequestProperty("Accept-Encoding","gzip,deflate,sdch");

			//logger.log("open stream");

			dout = hc.openOutputStream();
			dout.write(postBytes);
			dout.flush();

			//logger.log("stream flushed");

			int rc = hc.getResponseCode();

			logger.log("response code " + rc);

			if (rc != HttpConnection.HTTP_OK) {
				logger.status("Servicio inactivo.");
				logger.log("HTTP response code: " + rc);
				return null;
			}

			//logger.log("open input");

			logger.status("Recibiendo datos...");

			is = hc.openInputStream();

			//
			String type = hc.getType();

			//logger.log("inp type:" + type);

			// Get the length and process the data
			int len = (int) hc.getLength();

			//logger.log("inp len:" + len);

			int ch;
			isr = new InputStreamReader(is, "UTF-8");
			StringBuffer sb = new StringBuffer();

			//logger.log("reading");
			while ((ch = isr.read()) != -1) {
				sb.append((char) ch);
			}

			//logger.log("end of reading");
			res = sb.toString();
		} catch (Exception ex) {

			logger.log("HTTP Error: " + ex.getClass() + " " + ex.getMessage());

			throw ex;
		} finally {
			try {
				if (isr != null) {
					isr.close();
				}
			} catch (Exception e) {
			}
			try {
				if (is != null) {
					is.close();
				}
			} catch (Exception e) {
			}
			try {
				if (dout != null) {
					dout.close();
				}
			} catch (Exception e) {
			}
			try {
				if (hc != null) {
					hc.close();
				}
			} catch (Exception e) {
			}
		}
		return res;
	}
}